<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>栈测试</title>
</head>

<body>
  <script>
    function smartRepeat(str) {
      let result = ''
      let i = 0
      let numberStack = []
      let stringStack = []

      while (i < str.length - 1) {
        // 获取字符串剩余部分
        rest = str.substring(i);
        if (/^\d+\[/.test(rest)) {
          // 遇见的是数字+[ 就将数组入栈，空字符串入栈
          // 得到这个数字
          let times = Number(rest.match(/^(\d+)\[/)[1]);
          numberStack.push(times)
          stringStack.push('')
          // 让指针后移数字长度+一个[的位置
          i += times.toString().length + 1
        } else if (/^\w+\]/.test(rest)) {
          // 遇到 ] 前面的数组或字母
          let word = rest.match(/^(\w+)\]/)[1]
          stringStack[stringStack.length - 1] = word
          i += word.length
        } else if (rest[0] === ']') {
          let times = numberStack.pop()
          let word = stringStack.pop()
          stringStack[stringStack.length - 1] += word.repeat(times);
          i++
        }
      }
      result = stringStack[0].repeat(numberStack[0])
      return result
    }

    str = '2[1[a]3[b]2[3[c]4[d]]]'
    let result = smartRepeat(str)
    console.log(result)
  </script>
</body>

</html>